const mongoose = require("mongoose"); // 引入mongo数据库
const Schema = mongoose.Schema; // 数据字段
const moment = require("moment"); // 引入moment库
const crypto = require("crypto");
const util = require("util");

const scrypt = util.promisify(crypto.scrypt);

// user模型===>users集合
const UserType = new Schema(
  {
    username: {
      type: String,
      required: true,
      unique: true,
    },
    password: {
      type: String,
      required: true,
    },
    // 性别 取值【保密 0, 男 1, 女 2】
    gender: {
      type: Number,
      enum: [0, 1, 2],
      default: 0,
    },
    introduction: String, // 简介
    avatar: String, // 头像
    // 角色 取值【管理员 1, 编辑 2】
    role: {
      type: Number,
      enum: [1, 2],
      default: 2,
    },
    createdAt: String, // 创建时间
    updatedAt: String, // 更新时间
  },
  {
    timestamps: {
      currentTime: () => moment().format("YYYY-MM-DD HH:mm:ss"),
      createdAt: "createdAt",
      updatedAt: "updatedAt",
    },
  }
);

// 保存前处理密码加密
UserType.pre("save", async function (next) {
  if (this.isModified("password")) {
    const salt = crypto.randomBytes(16).toString("hex"); // 生成随机盐
    const hash = (await scrypt(this.password, salt, 64)).toString("hex"); // 使用scrypt加密
    this.password = `${salt}.${hash}`;
  }
  next();
});

// 校验密码
UserType.methods.comparePassword = async function (candidatePassword) {
  const [salt, key] = this.password.split(".");
  const hashedPassword = (await scrypt(candidatePassword, salt, 64)).toString("hex");
  return crypto.timingSafeEqual(Buffer.from(hashedPassword), Buffer.from(key));
};

const UserModel = mongoose.model("user", UserType);

module.exports = UserModel;
